﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace Hont.UMotionGraph
{
    public class MGVertexContainer : MonoBehaviour, IMoGraphContainer
    {
        public MeshFilter meshFilter;
        public MoGraphEffector[] effectors;
        protected List<IMoGraphEffector> mEffectorList;
        protected Vector3[] mUpdateMiddleValueArr;
        protected Vector3[] mSourceValueArr;
        protected Mesh mMesh;

        List<IMoGraphEffector> IMoGraphContainer.EffectorList { get { return mEffectorList; } }

        public virtual int Count { get { return mMesh.vertexCount; } }


        public void UpdateValue(Vector3[] values)
        {
            var vert = mMesh.vertices;

            for (int i = 0; i < mMesh.vertexCount; i++)
            {
                vert[i] = values[i] - meshFilter.transform.position;
            }

            mMesh.vertices = vert;
        }

        protected virtual void Awake()
        {
            mMesh = meshFilter.mesh;
            mEffectorList = new List<IMoGraphEffector>();
            mEffectorList.AddRange(effectors);
            mEffectorList.ForEach(m => m.Init(this));

            mUpdateMiddleValueArr = new Vector3[mMesh.vertexCount];
            mSourceValueArr = new Vector3[mMesh.vertexCount];
            for (int i = 0; i < mSourceValueArr.Length; i++)
            {
                mSourceValueArr[i] = meshFilter.transform.position + mMesh.vertices[i];
            }
        }

        protected virtual void Update()
        {
            for (int i = 0; i < mUpdateMiddleValueArr.Length; i++)
            {
                mUpdateMiddleValueArr[i] = GetValue(0, i);
            }

            for (int i = 0; i < mEffectorList.Count; i++)
            {
                var item = mEffectorList[i];

                for (int j = 0; j < mMesh.vertexCount; j++)
                {
                    mUpdateMiddleValueArr[j] = item.Execute(j, mUpdateMiddleValueArr[j]);
                }
            }

            UpdateValue(mUpdateMiddleValueArr);
        }

        public virtual Vector3 GetValue(int type, int inx)
        {
            return mSourceValueArr[inx];
        }
    }
}
